package service

import (
	"context"
	"encoding/json"
	"fmt"
	"fx_swift_schedule/api"
	"fx_swift_schedule/internal/model"
	"fx_swift_schedule/pkg/code"
	"fx_swift_schedule/pkg/global"
	"fx_swift_schedule/pkg/internalerrors"
	"fx_swift_schedule/pkg/logger"
	"fx_swift_schedule/pkg/mail"
	"fx_swift_schedule/pkg/temple"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/golang-module/carbon/v2"
	"github.com/shopspring/decimal"
	"github.com/spf13/cast"
)

type IIfcCallBackSrv interface {
	// 换汇交易回调
	Tp1003CallBack(ctx context.Context, req *api.Tp1003CallBackReq) error
	// 国际汇款回调
	Tp1005CallBack(ctx context.Context, req *api.Tp1005CallBackReq) error
	// VA开户回调
	VAInfoCallBack(ctx context.Context, req *api.VAInfoCallBackReq) error
	// 国内汇款回调
	Tp2001CallBack(ctx context.Context, req *api.Tp2001CallBackReq) error
	// 贸易到账回调
	Tp2007CallBack(ctx context.Context, req *api.Tp2007CallBackReq) error
	// 贸易订单申请回调
	Tp1012CallBack(ctx context.Context, req *api.Tp1012CallBackReq) error
	// 收款流水和贸易订单关联回调
	Tp2009CallBack(ctx context.Context, req *api.Tp2009CallBackReq) error
	//商户入网回调
	MerChantCallBack(ctx context.Context, req *api.MerVACallBackReq) error
}
type ifcCallBackSrv struct {
}

func NewIfcCallBackSrv() IIfcCallBackSrv {
	return &ifcCallBackSrv{}
}

// 换汇交易回调
func (c *ifcCallBackSrv) Tp1003CallBack(ctx context.Context, req *api.Tp1003CallBackReq) error {
	var (
		err error
	)
	g.Dump("换汇交易回调参数打印：", req)
	if req.Code == "S00000" && req.Message == "Success" {
		if _, err = global.GFDB.Ctx(ctx).Model("ifcgate_exchange_currency").Data(g.Map{
			"status": "SUCCESS",
		}).Where("biz_flow=?", req.BizFlow).Update(); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		err = ExchangeCommission(req.BizFlow)
	} else {
		if _, err = global.GFDB.Model("ifcgate_exchange_currency").Data(g.Map{
			"status": "FAIL", "msg": req.Message,
		}).Where("biz_flow=?", req.BizFlow).Update(); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	}
	return nil
}

// 国际汇款回调
func (c *ifcCallBackSrv) Tp1005CallBack(ctx context.Context, req *api.Tp1005CallBackReq) error {
	var (
		itRecordObj *model.IfcgateInternationTransferRecord
		ipOnj       *model.IfcgateInternationPayee
		merchantObj *model.IFCGateMerChantVAInfo
		err         error
	)
	g.Dump("国际汇款回调参数打印：", req)
	if _, err = global.GFDB.Ctx(ctx).Model("ifcgate_internation_transfer_record").Data(g.Map{
		"status": req.Status, "fee_amt": req.FeeAmt, "fee_currency": req.FeeCurrency, "message": req.Message}).
		Where("quote_id=? and biz_flow=?", req.QuoteId, req.BizFlow).Update(); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_internation_transfer_record").
		Where("quote_id=? and biz_flow=?", req.QuoteId, req.BizFlow).Scan(&itRecordObj); err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_internation_payee").
		Where("id=?", itRecordObj.PayeeId).Scan(&ipOnj); err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	if err = global.GFDB.Ctx(ctx).Model("ifcgate_merchant_va_info").
		Where("merchant_no=?", ipOnj.MerchantNo).Scan(&merchantObj); err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	if req.Status == "SUCC" { // 需要计算佣金
		if err = PayCommission(req.CountryCode, req.PayType, itRecordObj.MerchantNo, itRecordObj.Account,
			req.DebitCurrency, req.BizFlow, cast.ToFloat64(req.DebitAmount)); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		if cast.ToFloat64(req.Rate) != 1 {
			if err = ExchangeRmbCommission(req.BizFlow, itRecordObj.MerchantNo, req.DebitCurrency, req.ArriveCurrency, itRecordObj.Account,
				cast.ToFloat64(req.DebitAmount), cast.ToFloat64(req.Rate)); err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, err.Error())
			}
		}
	}

	// 发邮件
	g.Go(ctx, func(ctx context.Context) {
		mail.SendMail(merchantObj.Email, temple.DomesticTransferStr, "付款通知", model.InternationPayeeEmail{
			PayeeName:  ipOnj.PayeeFirstName + ipOnj.PayeeLastName,
			BankAcctNo: ipOnj.PayeeBankAccountNo,
			Money:      req.DebitAmount,
			Currency:   req.DebitCurrency,
		})
	}, func(ctx context.Context, exception error) {
		logger.SugarLogger.Error(exception)
	})
	return nil
}

// 国内汇款回调
func (c *ifcCallBackSrv) Tp2001CallBack(ctx context.Context, req *api.Tp2001CallBackReq) error {
	var (
		merchantObj *model.IFCGateMerChantVAInfo
		dtRecordObj *model.IfcgateDomesticTransferRecord
		dpOnj       *model.IfcgateDomesticPayee
		tp3001Res   *api.Tp3001Res
		err         error
	)
	g.Dump("国内汇款回调参数打印：", req)
	if err = global.GFDB.Ctx(ctx).Model("ifcgate_domestic_transfer_record").
		Where("mer_order_no=? and biz_flow_no=?", req.MerOrderNo, req.BizFlowNo).Scan(&dtRecordObj); err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if len(req.PayeeList[0].Status) > 0 {
		merchantToken, _ := GetMerchantToToken(dtRecordObj.MerchantNo)
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		tp3001Res, err = PostTp3001(&api.Tp3001Req{
			BizFlowNo: req.BizFlowNo,
		}, merchantToken)
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}

		if _, err = global.GFDB.Ctx(ctx).Model("ifcgate_domestic_transfer_record").Data(g.Map{
			"status": req.PayeeList[0].Status, "resp_code": req.PayeeList[0].RespCode, "resp_desc": req.PayeeList[0].RespDesc,
			"fee_currency": tp3001Res.Body.FeeCurrency, "fee_amount": tp3001Res.Body.FeeAmount / 100}).
			Where("mer_order_no=? and biz_flow_no=?",
				req.MerOrderNo, req.BizFlowNo).Update(); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}

		if err = global.GFDB.Ctx(ctx).Model("ifcgate_domestic_payee").
			Where("id=?", dtRecordObj.PayeeId).Scan(&dpOnj); err != nil {
			return internalerrors.New(code.ErrUnknown, err.Error())
		}

		if err = global.GFDB.Ctx(ctx).Model("ifcgate_merchant_va_info").
			Where("merchant_no=?", dpOnj.MerchantNo).Scan(&merchantObj); err != nil {
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		if req.PayeeList[0].Status == "1" { // 需要计算佣金
			tradeType := ""
			if dtRecordObj.TradeCodeType == "TRADE" || dtRecordObj.TradeCodeType == "TRADE_OFFLINE" || dtRecordObj.TradeCodeType == "E_COMMERCE" {
				tradeType = "00"
			} else {
				tradeType = "01"
			}
			if len(tradeType) > 0 {
				if err = RmbCommission(tradeType, req.DebitCurrency,
					dtRecordObj.MerchantNo, dtRecordObj.Account, req.SettlementType, req.BizFlowNo, req.DebitAmount/100); err != nil {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, err.Error())
				}

				if req.DebitCurrency != "CNY" {
					if err = ExchangeRmbCommission(req.BizFlowNo, dtRecordObj.MerchantNo,
						req.DebitCurrency, "CNY", dtRecordObj.Account, req.DebitAmount/100, req.Rate); err != nil {
						logger.SugarLogger.Error(err)
						return internalerrors.New(code.ErrUnknown, err.Error())
					}
				}
			}
		}
		// 发邮件
		g.Go(ctx, func(ctx context.Context) {
			mail.SendMail(merchantObj.Email, temple.DomesticTransferStr, "付款通知", model.DomesticPayeeEmail{
				BranchName: dpOnj.BranchName,
				PayeeName:  dpOnj.PayeeName,
				BankAcctNo: dpOnj.BankAcctNo[len(dpOnj.BankAcctNo)-4:],
				Currency:   req.DebitCurrency,
				Money:      decimal.NewFromFloat(req.DebitAmount).Div(decimal.NewFromFloat(100)).String(),
			})
		}, func(ctx context.Context, err error) {
			logger.SugarLogger.Error(err)
		})
	}
	return err
}

// va开户回调
func (c *ifcCallBackSrv) VAInfoCallBack(ctx context.Context, req *api.VAInfoCallBackReq) error {
	var (
		err               error
		vaInfoCallBackObj *model.IFCGateVAInfoCallBack
		vaInfoObj         *model.IFCGateMerChantVAInfo
	)
	g.Dump("va开户回调参数打印：", req)
	if err = global.GFDB.Model("ifcgate_vainfo_call_back").
		Where("mer_order_no=? and biz_flow=?", req.MerOrderNo, req.BizFlow).
		Scan(&vaInfoCallBackObj); err != nil {
		logger.SugarLogger.Error()
		return internalerrors.New(code.ErrUnknown, "数据查询错误")
	}
	if vaInfoCallBackObj != nil {
		err = global.GFDB.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
			if _, err = tx.Model("ifcgate_vainfo_call_back").
				Data(g.Map{"account_name": req.AccountName, "account_no": req.AccountNo, "code_value": req.CodeValue,
					"code_name": req.CodeName, "bank_name": req.BankName, "bank_address": req.BankAddress,
					"area": req.Area, "bank_code": req.BankCode, "branch_code": req.BranchCode, "currency": req.Currency,
					"status": req.Status, "remark": req.Remark}).
				Where("mer_order_no=? and biz_flow=?", req.MerOrderNo, req.BizFlow).Update(); err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "VA开户回调信息更新异常")
			}
			if _, err = tx.Model("ifcgate_va_info").Data(g.Map{"status": req.Status, "remark": req.Remark}).
				Where("mer_order_no=? and biz_flow=?", req.MerOrderNo, req.BizFlow).Update(); err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "VA开户资料更新异常")
			}
			return nil
		})
		if req.Status == "ON" {
			if err = global.GFDB.Model("ifcgate_merchant_va_info").
				Where("merchant_no=?", vaInfoCallBackObj.MerChantNo).
				Scan(&vaInfoObj); err != nil {
				logger.SugarLogger.Error()
				return internalerrors.New(code.ErrUnknown, "数据查询错误")
			}
			err = Tp1014(&api.Tp1014Req{
				TradeCode:   "TP2007",
				CallbackUrl: global.ViperObj.GetString("callback.tp2007"),
			}, vaInfoObj.AccessToken)
		}
	}
	return err
}

// 贸易到账回调
func (c *ifcCallBackSrv) Tp2007CallBack(ctx context.Context, req *api.Tp2007CallBackReq) error {
	var (
		err             error
		tradeReceiptObj *model.IfcgateTradeReceipt
		vaCallBackInfo  *model.IFCGateVAInfoCallBack
		merchantObj     *model.IFCGateMerChantVAInfo
		account         string
	)
	defer func() {
		if r := recover(); r != nil {
			logger.SugarLogger.Error(err)
		}
	}()
	g.Dump("贸易到账回调参数打印：", req)

	if err = global.GFDB.Ctx(ctx).Model("ifcgate_trade_receipt").
		Where("va_account=? and flow_no=?", req.VaAccount, req.FlowNo).Scan(&tradeReceiptObj); err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if tradeReceiptObj == nil {
		if err = global.GFDB.Ctx(ctx).Model("ifcgate_vainfo_call_back").
			Where("account_no=?", req.VaAccount).Scan(&vaCallBackInfo); err != nil {
			return internalerrors.New(code.ErrUnknown, err.Error())
		}

		account, err = GetAccountToMerchantNo(vaCallBackInfo.MerChantNo)
		if err != nil {
			logger.SugarLogger.Error(err.Error())
			return internalerrors.New(code.ErrUnknown, err.Error())
		}

		if _, err = global.GFDB.Insert(ctx, "ifcgate_trade_receipt", &model.IfcgateTradeReceipt{
			FlowNo:              req.FlowNo,
			MerchantNo:          vaCallBackInfo.MerChantNo,
			Account:             account,
			ReceiveAmount:       req.ReceiveAmount,
			ReceiveCurrency:     req.ReceiveCurrency,
			VaAccount:           req.VaAccount,
			SenderName:          req.SenderName,
			SenderAccount:       req.SenderAccount,
			ReceiveTime:         carbon.CreateFromTimestamp(cast.ToInt64(req.ReceiveTime)).ToDateTimeString(),
			FeeAmount:           req.FeeAmount,
			FeeCurrency:         req.FeeCurrency,
			ActualReceiveAmount: req.ActualReceiveAmount,
			AvailableFlag:       req.AvailableFlag,
			ReceiveType:         req.ReceiveType,
			TradeComments:       req.TradeComments,
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		// 邮件通知
		if err = global.GFDB.Ctx(ctx).Model("ifcgate_merchant_va_info").
			Where("merchant_no=?", vaCallBackInfo.MerChantNo).Scan(&merchantObj); err != nil {
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		g.Go(ctx, func(ctx context.Context) {
			mail.SendMail(merchantObj.Email, temple.CollectionNoticeStr, "收款通知", &model.CollectMoneyEmail{
				Money:    cast.ToString(req.ActualReceiveAmount),
				Currency: req.ReceiveCurrency,
			})
		}, func(ctx context.Context, exception error) {
			logger.SugarLogger.Error(exception)
		})
	}
	return err
}

// 贸易订单申请回调
func (c *ifcCallBackSrv) Tp1012CallBack(ctx context.Context, req *api.Tp1012CallBackReq) error {
	var (
		err           error
		tp1013Res     *api.Tp1013Res
		tradeOrderObj *model.IfcgateTradeOrderCallBack
		merchantToken string
	)
	g.Dump("贸易订单申请回调参数打印：", req)

	if err = global.GFDB.Ctx(ctx).Model("ifcgate_trade_order_call_back").
		Where("mer_order_no=? and contract_no=?", req.MerOrderNo, req.ContractNo).
		Scan(&tradeOrderObj); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if req.Status == "SUCC" && tradeOrderObj != nil {
		if _, err = global.GFDB.Ctx(ctx).Model("ifcgate_trade_order_call_back").Data(g.Map{
			"status": req.Status, "message": req.Message}).
			Where("mer_order_no=? and contract_no=?", req.MerOrderNo, req.ContractNo).Update(); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		merchantToken, err = GetMerchantToToken(tradeOrderObj.MerchantNo)
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		logger.SugarLogger.Infof("商户号：%s,对应的token：%s", tradeOrderObj.MerchantNo, merchantToken)
		// 将贸易订单和收款流水进行相关联Tp1013
		tp1013Res, err = PostTp1013(&api.Tp1013Req{
			FlowNo:      tradeOrderObj.FlowNo,
			CallbackUrl: global.ViperObj.GetString("callback.tp2009"),
			ContactNo:   tradeOrderObj.ContractNo,
		}, merchantToken)
		if err != nil { // 关联失败
			if _, err = global.GFDB.Model("ifcgate_trade_receipt").Data(g.Map{
				"trade_status": "03", "trade_message": err.Error()}).
				Where("flow_no=?", tradeOrderObj.FlowNo).Update(); err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, err.Error())
			}
			return nil
		}
		if len(tp1013Res.Body.BizFlow) == 0 {
			logger.SugarLogger.Error(tp1013Res.Body.BizFlow)
			return internalerrors.New(code.ErrUnknown, "还原材料和收款流水关联失败")
		}
	} else if req.Status == "ACCEPT" && tradeOrderObj != nil {
		if _, err = global.GFDB.Ctx(ctx).Model("ifcgate_trade_order_call_back").Data(g.Map{
			"status": req.Status, "message": req.Message}).
			Where("mer_order_no=? and contract_no=?", req.MerOrderNo, req.ContractNo).Update(); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else if req.Status == "FAIL" && tradeOrderObj != nil {
		return global.GFDB.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
			if _, err = tx.Model("ifcgate_trade_order_call_back").Data(g.Map{
				"status": req.Status, "message": req.Message}).
				Where("mer_order_no=? and contract_no=?", req.MerOrderNo, req.ContractNo).Update(); err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, err.Error())
			}
			if _, err = tx.Model("ifcgate_trade_receipt").Data(g.Map{
				"trade_status": "03", "trade_message": req.Message}).
				Where("flow_no=?", tradeOrderObj.FlowNo).Update(); err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, err.Error())
			}
			return nil
		})
	}
	return err
}

// 收款流水和贸易订单关联回调
func (c *ifcCallBackSrv) Tp2009CallBack(ctx context.Context, req *api.Tp2009CallBackReq) error {
	var (
		err           error
		account       string
		tradeOrderObj *model.IfcgateTradeOrderCallBack
	)
	g.Dump("收款流水和贸易订单关联回调参数打印：", req)
	if req.Status == "02" {
		if err = global.GFDB.Ctx(ctx).Model("ifcgate_trade_order_call_back").
			Where("flow_no=? and contract_no=?", req.FlowNo, req.ContactNo).
			Scan(&tradeOrderObj); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}

		account, err = GetAccountToMerchantNo(tradeOrderObj.MerchantNo)
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}

		err = global.GFDB.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
			if _, err = tx.Insert("ifcgate_trade_order_mapping_flow", &model.IfcgateTradeOrderMappingFlow{
				MerchantNo:  tradeOrderObj.MerchantNo,
				FlowNo:      req.FlowNo,
				Account:     account,
				ContractNo:  req.ContactNo,
				Currency:    req.Currency,
				Amount:      req.Amount,
				FeeCurty:    req.FeeCurty,
				FeeAmt:      req.FeeAmt,
				ApproveTime: carbon.CreateFromTimestampMilli(req.ApproveTime).ToDateTimeString(),
				Status:      req.Status,
				Message:     req.Message,
			}); err != nil {
				return internalerrors.New(code.ErrUnknown, err.Error())
			}
			if _, err = tx.Model("ifcgate_trade_receipt").Data(g.Map{
				"trade_status":  req.Status,
				"trade_message": req.Message,
			}).Where("flow_no=?", req.FlowNo).Update(); err != nil {
				return internalerrors.New(code.ErrUnknown, err.Error())
			}
			return nil
		})
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		if err = CollectionCommission(req.FlowNo, req.ContactNo); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else {
		if _, err = global.GFDB.Model("ifcgate_trade_receipt").Data(g.Map{
			"trade_status":  req.Status,
			"trade_message": req.Message,
		}).Where("flow_no=?", req.FlowNo).Update(); err != nil {
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	}
	return nil
}

// 商户入网回调
func (c *ifcCallBackSrv) MerChantCallBack(ctx context.Context, req *api.MerVACallBackReq) error {
	g.Dump("商户入网回调参数打印：", req)
	var (
		err         error
		ottPyaToken string
		merchantObj *model.IFCGateMerChantVAInfo
	)

	if req == nil {
		logger.SugarLogger.Info("回调数据异常")
	}

	//当入网资料入库异常的时候临时保存，用于数据恢复
	tmpStr, _ := json.Marshal(req)
	if _, err = global.GFDB.Ctx(ctx).Model("ifcgate_merchant_va_tmp").
		Data(g.Map{"req_backup": string(tmpStr)}).Where("req_backup=?", req.BizFlow).Update(); err != nil {
		logger.SugarLogger.Error(err)
	}

	if err = global.GFDB.Model("ifcgate_merchant_va_info").
		Where("mer_order_no=?", req.MerOrderNo).Scan(&merchantObj); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if merchantObj != nil {
		if req.Code == "S00000" {
			err = global.GFDB.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
				if _, err = tx.Model("ifcgate_merchant_va_info").
					Data(g.Map{"biz_flow": req.BizFlow, "merchant_no": req.MerchantNo,
						"authorize_code": req.AuthorizeCode, "status": req.Status, "message": req.Message, "mer_name_en": req.MerNameEn}).
					Where("mer_order_no=?", req.MerOrderNo).Update(); err != nil {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, "更新异常")
				}
				if _, err = tx.Model("ifcgate_company_user").Data(g.Map{"merchant_no": req.MerchantNo}).
					Where("account=?", merchantObj.Account).Update(); err != nil {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, "更新异常")
				}
				return err
			})

			// 获取merchantNo对应的ottPyaToken
			ottPyaToken, err = NewAccessToken().GetAccessToken(ctx, req.MerOrderNo, req.AuthorizeCode)
			if err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, err.Error())
			}

			if err == nil {
				if _, err = g.Redis().Set(ctx, req.MerchantNo, ottPyaToken); err != nil {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, err.Error())
				}
			}
		} else {
			//如何审核返回FAIL即说明该商户被禁止入网，则注销掉该用户账号，并且将订单失效掉
			//if req.Status == "FAIL" {
			//先失效掉该入网申请单
			//_, err := global.GFDB.Model("ifcgate_merchant_va_info").Where("mer_order_no", req.MerOrderNo).Delete()
			//if err != nil {
			//	logger.SugarLogger.Error(err)
			//	return internalerrors.New(code.ErrUnknown, "商户入网申请单删除异常")
			//}
			//注销该账号
			//	_, err = global.GFDB.Model("ifcgate_agent").Where("account", merchantObj.Account).Delete()
			//	if err != nil {
			//		logger.SugarLogger.Error(err)
			//		return internalerrors.New(code.ErrUnknown, "账号注销异常")
			//	}
			//} else {
			statusStr := req.Status
			if statusStr == "REFUSE" {
				statusStr = "PENDING"
			}
			err = global.GFDB.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
				if _, err = tx.Model("ifcgate_merchant_va_info").
					Data(g.Map{"biz_flow": req.BizFlow, "status": statusStr, "message": req.Message}).
					Where("mer_order_no=?", req.MerOrderNo).Update(); err != nil {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, "更新异常")
				}
				return err
			})
		}

		//}

		//邮件通知入网结果
		if req.Status == "SUCC" {
			g.Go(ctx, func(ctx context.Context) {
				mail.SendMail(merchantObj.Email, temple.SendSuccEmailStr, "认证通知", "")
			}, func(ctx context.Context, exception error) {
				logger.SugarLogger.Error(exception)
			})
		} else if req.Status == "FAIL" {
			g.Go(ctx, func(ctx context.Context) {
				mail.SendMail(merchantObj.Email, temple.SendFailEmailStr, "认证通知", "")
			}, func(ctx context.Context, exception error) {
				logger.SugarLogger.Error(exception)
			})
		} else {
			g.Go(ctx, func(ctx context.Context) {
				mail.SendMail(merchantObj.Email, temple.SendRefuseEmailStr, "认证通知", "")
			}, func(ctx context.Context, exception error) {
				logger.SugarLogger.Error(exception)
			})
		}
	}
	return nil
}

// 换汇佣金计算
func ExchangeCommission(bizFlow string) error {
	var (
		err                                   error
		ifcgateExchangeInfo                   *model.IfcgateExchangeCurrency
		companyIfcgateFee                     *model.IfcgateFee
		defaultIfcgateFee                     *model.IfcgateFee
		agentIfcgateFee                       *model.IfcgateFee
		commissionValue, agentCommissionValue string
		agentReteDiff                         float64
		reteDiff, originalRate                float64
	)
	if err = global.GFDB.Model("ifcgate_exchange_currency").
		Where("biz_flow=? and status='SUCCESS'", bizFlow).Scan(&ifcgateExchangeInfo); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 默认手续
	if err = global.GFDB.Model("ifcgate_fee").
		Where("fee_type='03' and status='1'").
		Scan(&defaultIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 企业
	if err = global.GFDB.Model("ifcgate_fee").
		Where("merchant_no=? and fee_type='00' and status='1'", ifcgateExchangeInfo.MerchantNo).
		Scan(&companyIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 代理商
	if err = global.GFDB.Model("ifcgate_fee").
		Where("agent_account=? and fee_type='01' and status='1'", ifcgateExchangeInfo.Account).
		Scan(&agentIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	tradeAmount := cast.ToFloat64(ifcgateExchangeInfo.SellAmount)
	logger.SugarLogger.Infof("卖出价格：%f", tradeAmount)

	if len(companyIfcgateFee.AgentAccount) == 0 { //企业没有代理商，计算boss赚取企业的佣金
		//  boss赚代企业
		reteDiff = companyIfcgateFee.ExchangeRateDiff - defaultIfcgateFee.ExchangeRateDiff
		logger.SugarLogger.Infof("汇率差：%f", reteDiff)

		if reteDiff < 0 {
			originalRate = cast.ToFloat64(ifcgateExchangeInfo.Rate) / (1 + companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)

		} else {
			originalRate = cast.ToFloat64(ifcgateExchangeInfo.Rate) / (1 - companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)
		}
		// 佣金=卖出金额 * 原始汇率 * 汇率差
		commissionValue = fmt.Sprintf("%.4f", tradeAmount*originalRate*reteDiff)
		logger.SugarLogger.Infof("boos佣金收入为：%s", commissionValue)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         ifcgateExchangeInfo.MerchantNo,
			TradeNo:            ifcgateExchangeInfo.BizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "exchange",
			ExchangeRateSource: companyIfcgateFee.ExchangeRateSource,
			TradeAmount:        cast.ToFloat64(ifcgateExchangeInfo.SellAmount),
			TradeCurrency:      ifcgateExchangeInfo.SellCurrency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: ifcgateExchangeInfo.SellCurrency,
			FixedAmount:        0,
			FixedCurrency:      "",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else {
		// 原始汇率计算方式：正数：实时汇率/(1 - 企业实时汇率)；负数：实时汇率/(1 + 企业实时汇率)
		// 代理赚企业
		agentReteDiff = companyIfcgateFee.ExchangeRateDiff - agentIfcgateFee.ExchangeRateDiff
		logger.SugarLogger.Infof("代理商汇率差：%f", agentReteDiff)

		if agentReteDiff < 0 {
			originalRate = cast.ToFloat64(ifcgateExchangeInfo.Rate) / (1 + companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)

		} else {
			originalRate = cast.ToFloat64(ifcgateExchangeInfo.Rate) / (1 - companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)
		}
		// 佣金=卖出金额 * 原始汇率 * 汇率差
		agentCommissionValue = fmt.Sprintf("%.4f", tradeAmount*originalRate*agentReteDiff)
		logger.SugarLogger.Infof("代理商佣金收入为：%s", agentCommissionValue)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            agentIfcgateFee.AgentAccount,
			MerchantNo:         ifcgateExchangeInfo.MerchantNo,
			TradeNo:            ifcgateExchangeInfo.BizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "exchange",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        tradeAmount,
			TradeCurrency:      ifcgateExchangeInfo.SellCurrency,
			CommissionAmount:   cast.ToFloat64(agentCommissionValue),
			CommissionCurrency: ifcgateExchangeInfo.SellCurrency,
			FixedAmount:        0,
			FixedCurrency:      "",
			BudgetSign:         1,
			AccountType:        "agent",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		//  boss赚代理商
		reteDiff = agentIfcgateFee.ExchangeRateDiff - defaultIfcgateFee.ExchangeRateDiff
		logger.SugarLogger.Infof("boss商汇率差：%f", reteDiff)

		if reteDiff < 0 {
			originalRate = cast.ToFloat64(ifcgateExchangeInfo.Rate) / (1 + companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)

		} else {
			originalRate = cast.ToFloat64(ifcgateExchangeInfo.Rate) / (1 - companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)
		}
		// 佣金=卖出金额 * 原始汇率 * 汇率差
		commissionValue = fmt.Sprintf("%.4f", tradeAmount*originalRate*reteDiff)
		logger.SugarLogger.Infof("boos佣金收入为：%s", commissionValue)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         ifcgateExchangeInfo.MerchantNo,
			TradeNo:            ifcgateExchangeInfo.BizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "exchange",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        cast.ToFloat64(ifcgateExchangeInfo.SellAmount),
			TradeCurrency:      ifcgateExchangeInfo.SellCurrency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: ifcgateExchangeInfo.SellCurrency,
			FixedAmount:        0,
			FixedCurrency:      "",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	}

	return err
}

func ExchangeRmbCommission(bizFlow, merchantNo, sellCurrency, commissionCurrency, account string, tradeAmount, tradeFate float64) error {
	var (
		err                                   error
		companyIfcgateFee                     *model.IfcgateFee
		defaultIfcgateFee                     *model.IfcgateFee
		agentIfcgateFee                       *model.IfcgateFee
		commissionValue, agentCommissionValue string
		reteDiff, originalRate, agentReteDiff float64
	)

	// 默认手续
	if err = global.GFDB.Model("ifcgate_fee").
		Where("fee_type='03' and status='1'").
		Scan(&defaultIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 企业
	if err = global.GFDB.Model("ifcgate_fee").
		Where("merchant_no=? and fee_type='00' and status='1'", merchantNo).
		Scan(&companyIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 代理商
	if err = global.GFDB.Model("ifcgate_fee").
		Where("agent_account=? and fee_type='01' and status='1'", account).
		Scan(&agentIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	if len(companyIfcgateFee.AgentAccount) == 0 { //企业没有代理商，计算boss赚取企业的佣金
		//  boss赚代企业
		reteDiff = companyIfcgateFee.ExchangeRateDiff - defaultIfcgateFee.ExchangeRateDiff
		logger.SugarLogger.Infof("汇率差：%f", reteDiff)

		if reteDiff < 0 {
			originalRate = cast.ToFloat64(tradeFate) / (1 + companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)

		} else {
			originalRate = cast.ToFloat64(tradeFate) / (1 - companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)
		}
		commissionValue = fmt.Sprintf("%.4f", tradeAmount*originalRate*reteDiff)
		logger.SugarLogger.Infof("boos佣金收入为：%s", commissionValue)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         merchantNo,
			TradeNo:            bizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "exchange",
			ExchangeRateSource: companyIfcgateFee.ExchangeRateSource,
			TradeAmount:        tradeAmount,
			TradeCurrency:      sellCurrency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: commissionCurrency,
			FixedAmount:        0,
			FixedCurrency:      "",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else {
		//汇率计算方式：正数：实时汇率-实时汇率*汇差；负数：实时汇率+实时汇率*汇差
		// 代理赚企业
		agentReteDiff = companyIfcgateFee.ExchangeRateDiff - agentIfcgateFee.ExchangeRateDiff
		logger.SugarLogger.Infof("汇率差：%f", agentReteDiff)

		if agentReteDiff < 0 {
			originalRate = cast.ToFloat64(tradeFate) / (1 + companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)

		} else {
			originalRate = cast.ToFloat64(tradeFate) / (1 - companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)
		}
		agentCommissionValue = fmt.Sprintf("%.4f", tradeAmount*originalRate*agentReteDiff)
		logger.SugarLogger.Infof("代理商佣金收入为：%s", agentCommissionValue)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            agentIfcgateFee.AgentAccount,
			MerchantNo:         merchantNo,
			TradeNo:            bizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "exchange",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        tradeAmount,
			TradeCurrency:      sellCurrency,
			CommissionAmount:   cast.ToFloat64(agentCommissionValue),
			CommissionCurrency: commissionCurrency,
			FixedAmount:        0,
			FixedCurrency:      "",
			BudgetSign:         1,
			AccountType:        "agent",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		//  boss赚代理商
		reteDiff = agentIfcgateFee.ExchangeRateDiff - defaultIfcgateFee.ExchangeRateDiff
		logger.SugarLogger.Infof("汇率差：%f", reteDiff)

		if reteDiff < 0 {
			originalRate = cast.ToFloat64(tradeFate) / (1 + companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)

		} else {
			originalRate = cast.ToFloat64(tradeFate) / (1 - companyIfcgateFee.ExchangeRateDiff)
			logger.SugarLogger.Infof("原始汇率：%f", originalRate)
		}
		commissionValue = fmt.Sprintf("%.4f", tradeAmount*originalRate*reteDiff)
		logger.SugarLogger.Infof("boos佣金收入为：%s", commissionValue)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         merchantNo,
			TradeNo:            bizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "exchange",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        tradeAmount,
			TradeCurrency:      sellCurrency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: commissionCurrency,
			FixedAmount:        0,
			FixedCurrency:      "",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	}

	return err
}

// 收款佣金计算
func CollectionCommission(flowNo, contactNo string) error {
	var (
		err                                   error
		defaultIfcgateFee                     *model.IfcgateFee
		companyIfcgateFee                     *model.IfcgateFee
		agentIfcgateFee                       *model.IfcgateFee
		tradeOrderObj                         *model.IfcgateTradeOrderCallBack
		tradeOrderMappingObj                  *model.IfcgateTradeOrderMappingFlow
		feeDiff, fixedDiff                    float64
		agentFeeDiff, agentFixedDiff          float64
		commissionValue, agentCommissionValue string
	)
	if err = global.GFDB.Model("ifcgate_trade_order_call_back").
		Where("flow_no=? and contract_no=? and status='SUCC'", flowNo, contactNo).
		Scan(&tradeOrderObj); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	if err = global.GFDB.Model("ifcgate_trade_order_mapping_flow").
		Where("flow_no=? and contract_no=? and status='02'", flowNo, contactNo).
		Scan(&tradeOrderMappingObj); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 默认手续
	if err = global.GFDB.Model("ifcgate_fee").
		Where("fee_type='03' and status='1'").
		Scan(&defaultIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 企业
	if err = global.GFDB.Model("ifcgate_fee").
		Where("merchant_no=? and fee_type='00' and status='1'", tradeOrderObj.MerchantNo).
		Scan(&companyIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	// 代理商
	if err = global.GFDB.Model("ifcgate_fee").
		Where("agent_account=? and fee_type='01' and status='1'", tradeOrderObj.Account).
		Scan(&agentIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	tradeAmount := tradeOrderMappingObj.Amount
	logger.SugarLogger.Infof("交易金额:%f", tradeAmount)

	if len(companyIfcgateFee.AgentAccount) == 0 { // //企业没有代理商，计算boss赚取企业的佣金
		// 00-货物贸易 01-服务贸易
		if tradeOrderObj.TradeType == "00" {
			feeDiff = companyIfcgateFee.GtCollectionFee - defaultIfcgateFee.GtCollectionFee
			fixedDiff = companyIfcgateFee.GtCollectionFixedFee - defaultIfcgateFee.GtCollectionFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))

		} else if tradeOrderObj.TradeType == "01" {
			feeDiff = companyIfcgateFee.StCollectionFee - defaultIfcgateFee.StCollectionFee
			fixedDiff = companyIfcgateFee.StCollectionFixedFee - defaultIfcgateFee.StCollectionFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))

		}
		logger.SugarLogger.Infof("收款佣金为：%s", fmt.Sprintf("%.4f", tradeAmount*feeDiff))
		commissionValue = fmt.Sprintf("%.4f", tradeAmount*feeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         tradeOrderObj.MerchantNo,
			TradeNo:            tradeOrderMappingObj.FlowNo,
			TradeTime:          tradeOrderMappingObj.ApproveTime,
			CommissionType:     "collection",
			ExchangeRateSource: companyIfcgateFee.ExchangeRateSource,
			TradeAmount:        tradeAmount,
			TradeCurrency:      tradeOrderMappingObj.Currency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: tradeOrderMappingObj.Currency,
			FixedAmount:        fixedDiff,
			FixedCurrency:      "USD",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else {
		// 代理商赚取企业的
		// 00-货物贸易 01-服务贸易
		if tradeOrderObj.TradeType == "00" {
			agentFeeDiff = companyIfcgateFee.GtCollectionFee - agentIfcgateFee.GtCollectionFee
			agentFixedDiff = companyIfcgateFee.GtCollectionFixedFee - agentIfcgateFee.GtCollectionFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(agentFeeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(agentFixedDiff))

		} else if tradeOrderObj.TradeType == "01" {
			agentFeeDiff = companyIfcgateFee.StCollectionFee - agentIfcgateFee.StCollectionFee
			agentFixedDiff = companyIfcgateFee.StCollectionFixedFee - agentIfcgateFee.StCollectionFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(agentFeeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(agentFixedDiff))

		}
		logger.SugarLogger.Infof("收款佣金为：%s", fmt.Sprintf("%.4f", tradeAmount*agentFeeDiff))
		agentCommissionValue = fmt.Sprintf("%.4f", tradeAmount*agentFeeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            agentIfcgateFee.AgentAccount,
			MerchantNo:         tradeOrderObj.MerchantNo,
			TradeNo:            tradeOrderMappingObj.FlowNo,
			TradeTime:          tradeOrderMappingObj.ApproveTime,
			CommissionType:     "collection",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        tradeAmount,
			TradeCurrency:      tradeOrderMappingObj.Currency,
			CommissionAmount:   cast.ToFloat64(agentCommissionValue),
			CommissionCurrency: tradeOrderMappingObj.Currency,
			FixedAmount:        agentFixedDiff,
			FixedCurrency:      "USD",
			BudgetSign:         1,
			AccountType:        "agent",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}

		// boss赚取代理商的
		// 00-货物贸易 01-服务贸易
		if tradeOrderObj.TradeType == "00" {
			feeDiff = agentIfcgateFee.GtCollectionFee - defaultIfcgateFee.GtCollectionFee
			fixedDiff = agentIfcgateFee.GtCollectionFixedFee - defaultIfcgateFee.GtCollectionFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))

		} else if tradeOrderObj.TradeType == "01" {
			feeDiff = agentIfcgateFee.StCollectionFee - defaultIfcgateFee.StCollectionFee
			fixedDiff = agentIfcgateFee.StCollectionFixedFee - defaultIfcgateFee.StCollectionFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))

		}
		logger.SugarLogger.Infof("收款佣金为：%s", fmt.Sprintf("%.4f", tradeAmount*feeDiff))
		commissionValue = fmt.Sprintf("%.4f", tradeAmount*feeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         tradeOrderObj.MerchantNo,
			TradeNo:            tradeOrderMappingObj.FlowNo,
			TradeTime:          tradeOrderMappingObj.ApproveTime,
			CommissionType:     "collection",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        tradeAmount,
			TradeCurrency:      tradeOrderMappingObj.Currency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: tradeOrderMappingObj.Currency,
			FixedAmount:        fixedDiff,
			FixedCurrency:      "USD",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	}
	return err
}

// 人民币结汇佣金计算
func RmbCommission(tradeType, debitCurrency, merchantNo, account, settlementType, bizFlowNo string, debitAmount float64) error {
	logger.SugarLogger.Infof("交易类型：%s,扣款币种:%s,商户号:%s,代理商账户:%s,结汇类型:%s,流水号:%s,扣款金额:%f",
		tradeType, debitCurrency, merchantNo, account, settlementType, bizFlowNo, debitAmount)
	var (
		err                                   error
		defaultIfcgateFee                     *model.IfcgateFee
		companyIfcgateFee                     *model.IfcgateFee
		agentIfcgateFee                       *model.IfcgateFee
		feeDiff, fixedDiff                    float64
		agentFeeDiff, agentFixedDiff          float64
		commissionValue, agentCommissionValue string
	)
	// 默认手续
	if err = global.GFDB.Model("ifcgate_fee").
		Where("fee_type='03' and status='1'").
		Scan(&defaultIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 企业
	if err = global.GFDB.Model("ifcgate_fee").
		Where("merchant_no=? and fee_type='00' and status='1'", merchantNo).
		Scan(&companyIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	// 代理商
	if err = global.GFDB.Model("ifcgate_fee").
		Where("agent_account=? and fee_type='01' and status='1'", account).
		Scan(&agentIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	if len(companyIfcgateFee.AgentAccount) == 0 { //企业没有代理商，计算boss赚取企业的佣金
		// 00-普通结汇 10-极速结汇
		if settlementType == "00" {
			// 00-货物贸易 01-服务贸易
			if tradeType == "00" {
				feeDiff = companyIfcgateFee.GtPaymentFee - defaultIfcgateFee.GtPaymentFee
				fixedDiff = companyIfcgateFee.GtSpeedPaymentFee - defaultIfcgateFee.GtSpeedPaymentFee
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
			} else if tradeType == "01" {
				feeDiff = companyIfcgateFee.GtPaymentFee - defaultIfcgateFee.GtPaymentFee
				fixedDiff = companyIfcgateFee.GtSpeedPaymentFee - defaultIfcgateFee.GtSpeedPaymentFee
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
			}
		} else if settlementType == "10" {
			// 00-货物贸易
			if tradeType == "00" {
				feeDiff = (companyIfcgateFee.GtPaymentFee + companyIfcgateFee.GtSpeedPaymentFee) - (defaultIfcgateFee.GtPaymentFee + defaultIfcgateFee.GtSpeedPaymentFee)
				fixedDiff = (companyIfcgateFee.GtPaymentFixedFee + companyIfcgateFee.GtSpeedPaymentFixedFee) - (defaultIfcgateFee.GtPaymentFixedFee + defaultIfcgateFee.GtSpeedPaymentFixedFee)
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
			}
		}

		logger.SugarLogger.Infof("结汇佣金为：%s", fmt.Sprintf("%.4f", debitAmount*feeDiff))
		commissionValue = fmt.Sprintf("%.4f", debitAmount*feeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         merchantNo,
			TradeNo:            bizFlowNo,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "dTransfer",
			ExchangeRateSource: companyIfcgateFee.ExchangeRateSource,
			TradeAmount:        debitAmount,
			TradeCurrency:      debitCurrency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: debitCurrency,
			FixedAmount:        fixedDiff,
			FixedCurrency:      "CNY",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else {
		// 代理商赚取企业的佣金
		// 00-普通结汇 10-极速结汇
		if settlementType == "00" {
			// 00-货物贸易 01-服务贸易
			if tradeType == "00" {
				agentFeeDiff = companyIfcgateFee.GtPaymentFee - agentIfcgateFee.GtPaymentFee
				agentFixedDiff = companyIfcgateFee.GtPaymentFixedFee - agentIfcgateFee.GtPaymentFixedFee
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(agentFeeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(agentFixedDiff))
			} else if tradeType == "01" {
				agentFeeDiff = companyIfcgateFee.StPaymentFee - agentIfcgateFee.StPaymentFee
				agentFixedDiff = companyIfcgateFee.StPaymentFixedFee - agentIfcgateFee.StPaymentFixedFee
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(agentFeeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(agentFixedDiff))
			}
		} else if settlementType == "10" {
			// 00-货物贸易
			if tradeType == "00" {
				agentFeeDiff = (companyIfcgateFee.GtPaymentFee + companyIfcgateFee.GtSpeedPaymentFee) - (agentIfcgateFee.GtPaymentFee + agentIfcgateFee.GtSpeedPaymentFee)
				agentFixedDiff = (companyIfcgateFee.GtSpeedPaymentFixedFee + companyIfcgateFee.GtSpeedPaymentFixedFee) - (agentIfcgateFee.GtPaymentFixedFee + agentIfcgateFee.GtSpeedPaymentFixedFee)
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(agentFeeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(agentFixedDiff))
			}
		}

		logger.SugarLogger.Infof("结汇佣金为：%s", fmt.Sprintf("%.4f", debitAmount*agentFeeDiff))
		agentCommissionValue = fmt.Sprintf("%.4f", debitAmount*agentFeeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            agentIfcgateFee.AgentAccount,
			MerchantNo:         merchantNo,
			TradeNo:            bizFlowNo,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "dTransfer",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        debitAmount,
			TradeCurrency:      debitCurrency,
			CommissionAmount:   cast.ToFloat64(agentCommissionValue),
			CommissionCurrency: debitCurrency,
			FixedAmount:        agentFixedDiff,
			FixedCurrency:      "CNY",
			BudgetSign:         1,
			AccountType:        "agent",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		// boss赚取代理商的佣金
		// 00-普通结汇 10-极速结汇
		if settlementType == "00" {
			// 00-货物贸易 01-服务贸易
			if tradeType == "00" {
				feeDiff = agentIfcgateFee.GtPaymentFee - defaultIfcgateFee.GtPaymentFee
				fixedDiff = agentIfcgateFee.GtPaymentFixedFee - defaultIfcgateFee.GtPaymentFixedFee
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
			} else if tradeType == "01" {
				feeDiff = agentIfcgateFee.StPaymentFee - defaultIfcgateFee.StPaymentFee
				fixedDiff = agentIfcgateFee.StPaymentFixedFee - defaultIfcgateFee.StPaymentFixedFee
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
			}
		} else if settlementType == "10" {
			// 00-货物贸易
			if tradeType == "00" {
				feeDiff = (agentIfcgateFee.GtPaymentFee + agentIfcgateFee.GtSpeedPaymentFee) - (defaultIfcgateFee.GtPaymentFee + defaultIfcgateFee.GtSpeedPaymentFee)
				fixedDiff = (agentIfcgateFee.GtPaymentFixedFee + agentIfcgateFee.GtPaymentFixedFee) - (defaultIfcgateFee.GtSpeedPaymentFixedFee + defaultIfcgateFee.GtSpeedPaymentFixedFee)
				logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
				logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
			}
		}

		logger.SugarLogger.Infof("结汇佣金为：%s", fmt.Sprintf("%.4f", debitAmount*feeDiff))
		commissionValue = fmt.Sprintf("%.4f", debitAmount*feeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         merchantNo,
			TradeNo:            bizFlowNo,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "dTransfer",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        debitAmount,
			TradeCurrency:      debitCurrency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: debitCurrency,
			FixedAmount:        agentFixedDiff,
			FixedCurrency:      "CNY",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	}
	return err
}

// 国际付款佣金计算
func PayCommission(countryCode, payType, merchantNo, account, debitCurrency, bizFlow string, debitAmount float64) error {
	logger.SugarLogger.Infof("国家编码：%s,扣款币种:%s,商户号:%s,代理商账户:%s,付款方式:%s,流水号:%s,扣款金额:%f",
		countryCode, debitCurrency, merchantNo, account, payType, bizFlow, debitAmount)
	var (
		err                                   error
		defaultIfcgateFee                     *model.IfcgateFee
		companyIfcgateFee                     *model.IfcgateFee
		agentIfcgateFee                       *model.IfcgateFee
		feeDiff, fixedDiff                    float64
		aFeeDiff, aFixedDiff                  float64
		commissionValue, agentCommissionValue string
	)
	// 默认手续
	if err = global.GFDB.Model("ifcgate_fee").
		Where("fee_type='03' and status='1'").
		Scan(&defaultIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	// 企业
	if err = global.GFDB.Model("ifcgate_fee").
		Where("merchant_no=? and fee_type='00' and status='1'", merchantNo).
		Scan(&companyIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	// 代理商
	if err = global.GFDB.Model("ifcgate_fee").
		Where("agent_account=? and fee_type='01' and status='1'", account).
		Scan(&agentIfcgateFee); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	if len(companyIfcgateFee.AgentAccount) == 0 { //企业没有代理商，计算boss赚取企业的佣金
		if payType == "local" && countryCode == "HK" {
			feeDiff = companyIfcgateFee.HkLocalPaymentFee - defaultIfcgateFee.HkLocalPaymentFee
			fixedDiff = companyIfcgateFee.HkLocalPaymentFixedFee - defaultIfcgateFee.HkLocalPaymentFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
		} else if payType == "swift" {
			feeDiff = companyIfcgateFee.InternationalPaymentFee - defaultIfcgateFee.InternationalPaymentFee
			fixedDiff = companyIfcgateFee.InternationalPaymentFixedFee - defaultIfcgateFee.InternationalPaymentFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
		}
		logger.SugarLogger.Infof("国际付款佣金为：%s", fmt.Sprintf("%.4f", debitAmount*feeDiff))
		commissionValue = fmt.Sprintf("%.4f", debitAmount*feeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         merchantNo,
			TradeNo:            bizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "iTransfer",
			ExchangeRateSource: companyIfcgateFee.ExchangeRateSource,
			TradeAmount:        debitAmount,
			TradeCurrency:      debitCurrency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: debitCurrency,
			FixedAmount:        fixedDiff,
			FixedCurrency:      "USD",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else {
		// 代理商赚取企业的佣金
		if payType == "local" && countryCode == "HK" {
			aFeeDiff = companyIfcgateFee.HkLocalPaymentFee - agentIfcgateFee.HkLocalPaymentFee
			aFixedDiff = companyIfcgateFee.HkLocalPaymentFixedFee - agentIfcgateFee.HkLocalPaymentFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(aFeeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(aFixedDiff))
		} else if payType == "swift" {
			aFeeDiff = companyIfcgateFee.InternationalPaymentFee - agentIfcgateFee.InternationalPaymentFee
			aFixedDiff = companyIfcgateFee.InternationalPaymentFixedFee - agentIfcgateFee.InternationalPaymentFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(aFeeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(aFixedDiff))
		}
		logger.SugarLogger.Infof("国际付款佣金为：%s", fmt.Sprintf("%.4f", debitAmount*aFeeDiff))
		agentCommissionValue = fmt.Sprintf("%.4f", debitAmount*aFeeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            agentIfcgateFee.AgentAccount,
			MerchantNo:         merchantNo,
			TradeNo:            bizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "iTransfer",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        debitAmount,
			TradeCurrency:      debitCurrency,
			CommissionAmount:   cast.ToFloat64(agentCommissionValue),
			CommissionCurrency: debitCurrency,
			FixedAmount:        aFixedDiff,
			FixedCurrency:      "USD",
			BudgetSign:         1,
			AccountType:        "agent",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
		// boss赚取代理商的佣金
		if payType == "local" && countryCode == "HK" {
			feeDiff = agentIfcgateFee.HkLocalPaymentFee - defaultIfcgateFee.HkLocalPaymentFee
			fixedDiff = agentIfcgateFee.HkLocalPaymentFixedFee - defaultIfcgateFee.HkLocalPaymentFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
		} else if payType == "swift" {
			feeDiff = agentIfcgateFee.InternationalPaymentFee - defaultIfcgateFee.InternationalPaymentFee
			fixedDiff = agentIfcgateFee.InternationalPaymentFixedFee - defaultIfcgateFee.InternationalPaymentFixedFee
			logger.SugarLogger.Infof("手续费比例差值：%s", cast.ToString(feeDiff))
			logger.SugarLogger.Infof("固定费用差值：%s", cast.ToString(fixedDiff))
		}
		logger.SugarLogger.Infof("国际付款佣金为：%s", fmt.Sprintf("%.4f", debitAmount*feeDiff))
		commissionValue = fmt.Sprintf("%.4f", debitAmount*feeDiff)

		if _, err = global.GFDB.Model("ifcgate_commission_record").Insert(&model.IfcgateCommissionRecord{
			Account:            "admin",
			MerchantNo:         merchantNo,
			TradeNo:            bizFlow,
			TradeTime:          carbon.Now().ToDateTimeString(),
			CommissionType:     "iTransfer",
			ExchangeRateSource: agentIfcgateFee.ExchangeRateSource,
			TradeAmount:        debitAmount,
			TradeCurrency:      debitCurrency,
			CommissionAmount:   cast.ToFloat64(commissionValue),
			CommissionCurrency: debitCurrency,
			FixedAmount:        fixedDiff,
			FixedCurrency:      "USD",
			BudgetSign:         1,
			AccountType:        "boss",
		}); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	}
	return err
}
